# -*- coding: utf-8 -*-
'''
 Source file
 File name: urlstring.py
 Creation date: 06-10-2011
 Author: dassier

'''

import re

class UrlString(str):
    ''' Class to manage URL
    '''

    def __init__(self, value):
        ''' Initialisation
        '''
        super(UrlString, self).__init__()
        if self.is_url():
            # The object is an URL
            match_obj = re.match(u'^(\w+)://(.+)', self)
            self._proto = match_obj.group(1)
            path = match_obj.group(2)
            match_obj = re.match(u'(.+?)/(.+)', path)
            if match_obj is None:
                # No path in string, just server name
                self._server = path
                self._path = ""
            else:
                self._server = match_obj.group(1)
                self._path = match_obj.group(2)
        else:
            # Not an url
            self._proto = ""
            self._server = ""
            self._path = ""

    def is_url(self):
        ''' Return True if the object is an url
        '''
        match_obj = re.match(u'^\w+://.+', self)
        if match_obj is None:
            # Object is not an url
            return False
        else:
            return True

    def proto(self):
        ''' Return protocole
        '''
        return self._proto

    def server(self):
        ''' Return server name
        '''
        return self._server

    def path(self):
        ''' Return full path (exclude server)
        '''
        return self._path

    def split_dir(self):
        ''' Split path into its directory
        '''
        list_dir = self._path.strip('/').split('/')
        element = list_dir[-1]
        list_dir = list_dir[0:-1]
        return list_dir, element
